package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.AddCart;
import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.CartItem;
import csu.web.mypetstore.service.AccountService;

import com.alibaba.fastjson.JSON;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.math.BigDecimal;


public class CartUpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ArrayList<BigDecimal> bigDecimals = new ArrayList<>();
        HttpSession session = req.getSession();
        Cart cart = (Cart)session.getAttribute("cart");
        AddCart addCart = (AddCart) session.getAttribute("addCart");
        Iterator<CartItem> cartItems = cart.getAllCartItems();
        Iterator<CartItem> addCartItems = addCart.getAllCartItems();
        while (cartItems.hasNext()){
            CartItem cartItem = (CartItem) cartItems.next();
            try {
                String itemId = cartItem.getItem().getItemId();
                String quantityString = req.getParameter(itemId);
                int quantity = Integer.parseInt(quantityString);
                if(quantity != cartItem.getQuantity()){
                    cart.setQuantityByItemId(itemId, quantity);
                    bigDecimals.add(cartItem.getTotal());
                    while(addCartItems.hasNext()){
                        CartItem addCartItem = addCartItems.next();
                        try{

                            if(addCartItem.getItem().getItemId().equals(itemId)){
                                addCart.setQuantityByItemId(itemId, quantity);
                            }
                        }catch (Exception e){}
                    }
                    bigDecimals.add(addCart.getSubTotal());
                    if (quantity < 1) {
                        cartItems.remove();
                        addCartItems.remove();
                    }
                    break;
                }

            }catch (Exception e) {}
        }
        Account loginAccount = (Account) session.getAttribute("loginAccount");
        AccountService accountService = new AccountService();
        accountService.ReserveCart(loginAccount,cart);

        String result = JSON.toJSONString(bigDecimals);
        System.out.println(result);
        resp.setContentType("text/json");
        PrintWriter out = resp.getWriter();
        out.println(result);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
